<?php
/**
 * Created by PhpStorm.
 * User: hbt
 * Date: 2016/12/27
 * Time: 20:00
 */
namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Common\SmsController;
use App\Http\Requests\RegisterFormRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Response;
class UserController extends Controller{
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            if (session('userid')) {
                $user = User::find(session('userid'));
            } else {
                $user = '';
            }
            $data['user'] = $user;
            view()->share($data);
            return $next($request);
        });
    }
    public function login(Request $request){
        if($request->ajax()){
            $mobile=$request->get('mobile');
            $password=$request->get('password');
//            //验证验证码
//            if(!captcha_check($request->get('captcha'))){
//                return Response::json(['code'=>'0001','message'=>'验证码错误']);
//            }
            if($mobile==''){
                return Response::json(['code'=>'0001','message'=>'请填写手机号']);
            }
            if($password==''){
                return Response::json(['code'=>'0001','message'=>'请填写密码']);
            }
            $user=User::where('mobile',$mobile)->first();
            if(!$user){
                return Response::json(['code'=>'0001','message'=>'手机号错误']);
            }
            if(!Hash::check($password.$user->salt,$user->password)){ //匹配密码
                return Response::json(['code'=>'0001','message'=>'密码错误']);
            }
            session(['userid'=>$user->id]);
            session(['mobile'=>$user->mobile]);
            //session_start();
            //$_SESSION['mobile']=$user->mobile;
            $redirect_uri = $request->session()->pull('redirect_uri');
            return Response::json(['code'=>'0000','message'=>'登录成功','url'=>$redirect_uri]);
        }

        return view("Home::user.login");
    }

    public function register(Request $request){
        if($request->ajax()){
            $name=$request->get('name');
            $sex=$request->get('sex');
            $password=$request->get('password');
            $mobile=$request->get('mobile');
            $code=$request->get('code');
            $registerReq = new RegisterFormRequest();
            $validator = Validator::make($request->all(),
                $registerReq->rules(), $registerReq->messages(), $registerReq->attributes());
            if ($validator->fails()) {
                $messages = $validator->errors();
//            $message = $validator->messages->first();
                foreach ($messages->all() as $message) {
                    return Response::json([
                        'code' => '0001',
                        'message' => $message,
                    ]);
                }
            }
            $hasMobile=User::where('mobile',$request->get('mobile'))->first();
            if(count($hasMobile)>0){
                return Response::json(['code'=>'0001','message'=>'此手机号码已被注册']);
            }

            $veifymobile=SmsController::verifyCode($mobile,$code);
            if($veifymobile['code']!='0000'){
                return Response::json(['code'=>$veifymobile['code'],'message'=>$veifymobile['message']]);
            }
            $salt = str_random(8);//8位盐值;
            $hashedPwd = Hash::make($password . $salt);
            $user = [
                'name' => $name,
                'sex'=>$sex,
                'mobile'=>$mobile,
                'password' => $hashedPwd,
                'salt' => $salt,
                'create_time' => date('Y-m-d H:i:s', time()),
                'create_ip' => ip(),

            ];
            $result = User::create($user);
            if($result){
                session(['userid'=>$result->id]);
                return Response::json(['code'=>'0000','message'=>'注册成功']);
            }else{
                return Response::json(['code'=>'0002','message'=>'注册失败，请重试']);
            }
        }
        return view('home.register');
    }

    //个人中心
    public function center(){
        if(!session('userid')){
            echo '请先登录';exit;
        }
        return view('home.center');
    }
    public function safe(){
        if(!session('userid')){
            echo '请先登录';exit;
        }
       return view('home.safe');
    }

    //修改密码
    public function password(){
        return view('home.password');
    }

    //验证原密码
    public function authpassword(Request $request){
        $userid=session('userid');
        if(!$userid){
            return Response::json(['code'=>'0001','message'=>'请先登录']);
        }
        $user=User::find($userid);
        $oldpassword=$request->get('password');
        if(!Hash::check($oldpassword.$user->salt,$user->password)){ //匹配密码
            return Response::json(['code'=>'0001','message'=>'密码错误']);
        }else{
            return Response::json(['code'=>'0000','message'=>'密码匹配正确']);
        }
    }

    //设置新密码
    public function editpassword(Request $request){
        $userid=session('userid');
        if(!$userid){
            return Response::json(['code'=>'0001','message'=>'请先登录']);
        }
        $user=User::find($userid);
        $newpassword=$request->get('newpassword');
        $salt = str_random(8);//8位盐值;
        $hashedPwd = Hash::make($newpassword . $salt);
        $user->salt=$salt;
        $user->password=$hashedPwd;
        $result=$user->save();
        if($result){
            return Response::json(['code'=>'0000','message'=>'成功设置新密码']);
        }else{
            return Response::json(['code'=>'0001','message'=>'设置新密码失败，请重试']);
        }

    }

    public function mobile(){
        return view('home.mobile');
    }

    public function authmobile(Request $request){
        //$userid=session('userid');
        //if(!$userid){
        //    return Response::json(['code'=>'0001','message'=>'请先登录']);
        ///}
        $mobile=$request->get('mobile');
        $code=$request->get('code');


        $verify=SmsController::verifyCode($mobile,$code);
        if($verify['code']=='0000'){
             return Response::json($verify,JSON_UNESCAPED_UNICODE);
        }else{
            return Response::json($verify,JSON_UNESCAPED_UNICODE);
        }
    }

    public function editmobile(Request $request){
        $mobile=$request->get('newmobile');
        $code=$request->get('verfiycode');
        $verify=SmsController::verifyCode($mobile,$code);
        if($verify['code']=='0000'){
            $user=User::find(session('userid'));
            $user->mobile=$mobile;
            $userRes=$user->save();
            if($userRes){
                return Response::json($verify,JSON_UNESCAPED_UNICODE);
            }else{
                return Response::json(['code'=>'0002','message'=>'验证失败，请重试'],JSON_UNESCAPED_UNICODE);
            }
        }else{
            return Response::json($verify,JSON_UNESCAPED_UNICODE);
        }
    }


    public function findpassword(){
        return view('home.findpassword');
    }
    public function findmobile(Request $request){
        $mobile=$request->get('mobile');
        $code=$request->get('code');
        $user=User::where('mobile',$mobile)->first();
        if(count($user)==0){
            return Response::json(['code'=>'0001','message'=>'不存在此手机号']);
        }

        $verify=SmsController::verifyCode($mobile,$code);
        if($verify['code']=='0000'){
            session(['userid'=>$user->id]);
            return Response::json($verify,JSON_UNESCAPED_UNICODE);
        }else{
            return Response::json($verify,JSON_UNESCAPED_UNICODE);
        }
    }
    public function editpwd(Request $request){
        $userid=session('userid');
        $user=User::find($userid);
        $newpassword=$request->get('newpassword');
        $salt = str_random(8);//8位盐值;
        $hashedPwd = Hash::make($newpassword . $salt);
        $user->salt=$salt;
        $user->password=$hashedPwd;
        $result=$user->save();
        if($result){
            return Response::json(['code'=>'0000','message'=>'成功设置新密码']);
        }else{
            return Response::json(['code'=>'0001','message'=>'设置新密码失败，请重试']);
        }

    }

    public function quit(Request $request){
        if ($request->session()->has('userid')) {
            $is_forgotten = $request->session()->forget('userid');
            //session_start();
            if(session('mobile')){
                $request->session()->forget('mobile');
            }
            if ($is_forgotten===null)
                return Response::json(['code'=>'0000','message'=>'成功退出']);
        }

        return Response::json(['code'=>'0001','message'=>'退出失败']);
    }


    public function ishavemobile(Request $request){
        $hasMobile=User::where('mobile',$request->get('mobile'))->first();
        if(count($hasMobile)>0){
            return Response::json(['code'=>'0001','message'=>'此手机号码已被注册']);
        }else{
            return Response::json(['code'=>'0000','message'=>'此手机号码未被注册']);
        }
    }


   

}